# coding: utf-8
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout
from loguru import logger

from common import signalBus
from common.server import VideoModel
from components import DownloadingTaskCard, SuccessTaskCard


class TaskCardView(QWidget):
    """ 下载任务视图 """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.cards = []
        self.verticalLayout = QVBoxLayout(self)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)

    def addCard(self, card: QWidget):
        self.cards.append(card)
        self.verticalLayout.addWidget(card)

    def removeCard(self, card: QWidget):
        self.cards.remove(card)
        self.verticalLayout.removeWidget(card)
        card.deleteLater()


class DownloadingTaskView(TaskCardView):
    """ 下载任务视图 """
    finished = Signal(VideoModel)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.runCards = []
        signalBus.downloadSig.connect(self.addTask)

    def addTask(self, model: VideoModel):
        logger.info(f"addTask, model:  {model}")
        for card in self.cards:
            card: DownloadingTaskCard
            if card.title() == model.title:
                return
        card = DownloadingTaskCard(self)
        card.setModel(model)
        card.statusChanged.connect(self.onStatusChanged)
        self.addCard(card)

    def onStatusChanged(self, is_running: bool):
        for card in self.cards:
            card: DownloadingTaskCard
            if card.isSuccess():
                self.finished.emit(card.model)
                if card in self.runCards:
                    self.runCards.remove(card)
                self.removeCard(card)
            else:
                run_count = len(self.runCards)
                if run_count != 3:
                    card.start()
                    self.runCards.append(card)


class SuccessTaskView(TaskCardView):
    """ 成功任务视图 """

    def __init__(self, parent=None):
        super().__init__(parent)

    def addTask(self, model: VideoModel):
        card = SuccessTaskCard(self)
        card.setModel(model)
        self.addCard(card)
